import BackgroundImg from "@assets/bg01.jpg";
import BackgroundImg1 from "@assets/bg03.jpg";
import BackgroundImg2 from "@assets/bg04.jpg";
import BackgroundImg3 from "@assets/bg06.jpg";
import CustomizedButton from "@assets/customized_long_button.png";
import CustomizedRmk from "@assets/customized_rmk.png";
import GetButton from "@assets/get_long_button.png";
import GoButton from "@assets/go_button.png";
import IpImg from "@assets/ip.png";
import NowGetButton from "@assets/now_get_button.png";
import RegisterButton from "@assets/register_long_button.png";
import RegisterRmk from "@assets/register_rmk.png";
import ResultRmk from "@assets/result_rmk.png";
import BaseBackground from "@plugin/BaseBackground";
import EnhanceUseNavigate from "@plugin/EnhanceUseNavigate";
import Modal from "@plugin/Modal";
import { GoRegister } from "@utils";
import React, { Component } from "react";
import styles from "./index.module.scss";

import GetRmk from "@assets/award_get_rmk.png";
import NormalRmk from "@assets/normal_rmk.png";
import TPPGetRmk from "@assets/tpp_award_get_rmk.png";
import TppIRmk from "@assets/tpp_rmk.png";

import { getRewardLogDetial } from "@api";
import CopySuccess from "@assets/copy_success.png";
import {
  IsRegistered,
  getChannel,
  getCode,
  navigateToMiniHome,
  parseLinkWithHash,
} from "../../../utils";

import IQIYI from "@assets/iqiyi.png";
import KS from "@assets/ks.png";
import RedPackageCover from "@assets/red_package_cover.png";
import TPP from "@assets/tpp.png";
import TZL from "@assets/tzl.png";

import IQIYICARD from "@assets/aqiyi_card.png";
import KSCARD from "@assets/ks_card.png";
import TPPCARD from "@assets/tpp_card.png";
import TZLCARD from "@assets/tzl_card.png";

import copy from "copy-to-clipboard";
import { Toast } from "react-vant";
import MyRewardButton from "../../../plugin/MyRewardButton";
import {
  CampaignIds,
  GoToReceiveClick,
  HaPopupClosed,
  HaPopupOpen,
  getGiftType,
  setGiftType,
} from "../../../utils/ha.common";

const awardCards = {
  1: {
    type: "1",
    cover: TZLCARD,
    code: "xxxxxxxx",
    endDate: "2024/12/31 23:59前",
    rmk: NormalRmk,
    rmkClassName: "normal_rmk",
    title: TZL,
    haName: "tianzhenlan",
  },
  2: {
    type: "2",
    cover: KSCARD,
    code: "XXXXXXXXXX",
    endDate: "2023/xx/xx-xxxx/xx/xx",
    rmk: NormalRmk,
    rmkClassName: "normal_rmk",
    title: KS,
    haName: "kaishu",
  },
  3: {
    type: "3",
    cover: TPPCARD,
    code: "xxxxxxxxxxxxxxxx",
    password: "xxxxxx",
    endDate: "2026/11/30 00:00前",
    rmk: TppIRmk,
    rmkClassName: "tpp_rmk",
    title: TPP,
    haName: "taopiaopiao",
  },
  4: {
    type: "4",
    price: "￥78",
    name: "爱奇艺黄金VIP会员季卡",
    cover: IQIYICARD,
    code: "xxxx-xxxx-xxxx-xxxx",
    endDate: "2024/10/10 00:00前",
    rmk: NormalRmk,
    rmkClassName: "normal_rmk",
    title: IQIYI,
    haName: "iqiyi",
  },
};

class Index extends Component {
  constructor(props) {
    super(props);

    this.state = {
      registered: IsRegistered(),
      copySuccess: false,
      rewardId: "", // 抽奖记录id
      detail: undefined,
    };
  }

  async componentDidMount() {
    const search = new URLSearchParams(window.location.search);

    //根据小程序返回， 判读是否已注册。
    document.addEventListener("visibilitychange", () => {
      const hashParmas = parseLinkWithHash(window.location.href);
      hashParmas?.memberId &&
        sessionStorage.setItem("memberid", hashParmas?.memberId);

      this.setState({
        registered: IsRegistered(),
      });
    });

    // 待从接口加载抽奖详情
    const { data } = await getRewardLogDetial({ id: search.get("reward_id") });
    if (data) {
      this.setState({
        detail: data,
      });

      //设置埋点需要的缓存
      setGiftType(data.lottery_result);
    }

    window._ha("send", "action", "cny_activity2_receivepage_view", {
      channel: getChannel(),
      code: getCode(),
      gift_type: getGiftType(),
      is_member: IsRegistered() ? "member" : "notmember",
      campaign_id: CampaignIds.activity2,
    });
  }

  goRegiser = () => {
    GoRegister(
      `/pages/userPackage/FY2324_CNY_luckydraw_Register?fromPage=${encodeURIComponent(
        window.location.href
      )}&reward_id=${this.state.detail.id}`
    );

    window._ha("send", "action", "cny_activity2_receivepage_register_click", {
      code: getCode(),
      gift_type: getGiftType(),
      is_member: IsRegistered() ? "member" : "notmember",
      campaign_id: CampaignIds.activity2,
      channel: getChannel(),
    });
  };

  // 领取红包
  getPackage = async () => {
    if (!this.state.detail.prize_url) return Toast("未配置领取链接");
    window.location.href = this.state.detail.prize_url;
    GoToReceiveClick("hongbao");
  };

  // 复制码
  handlerCopy = (text, type = undefined) => {
    copy(text);
    this.setState({
      copySuccess: true,
    });

    HaPopupOpen(
      "CopyKeySuccessPopupWindow",
      "cny_activity2_popupwindow_open",
      CampaignIds.activity2
    );

    window._ha(
      "send",
      "action",
      type === "pass"
        ? "cny_activity2_receivepage_pincopy_click"
        : "cny_activity2_receivepage_codecopy_click",
      {
        campaign_id: CampaignIds.activity2,
        channel: getChannel(),
        code: getCode(),
        gift_type: getGiftType(),
        is_member: IsRegistered() ? "member" : "notmember",
      }
    );
  };

  closeCopySuccess = () => {
    this.setState({
      copySuccess: false,
    });

    HaPopupClosed(
      "CopyKeySuccessPopupWindow",
      "cny_activity2_popupwindow_close",
      CampaignIds.activity2
    );
  };

  render() {
    const { registered, copySuccess, detail } = this.state;
    if (!detail) return <></>;

    let BgImg = BackgroundImg;
    if (detail.lottery_result !== 5) {
      if (registered) {
        BgImg = BackgroundImg1;
      } else {
        BgImg = BackgroundImg3;
      }
    } else if (detail.lottery_result === 5) {
      BgImg = BackgroundImg2;
    }

    return (
      <>
        <BaseBackground
          backgroundImage={BgImg}
          showFlag={true}
          showMyAward={true}
        >
          {/* 红包封面 */}
          {detail.lottery_result === 5 && (
            <div className={styles.package_box}>
              {/* <div className={styles.result_title}>恭喜获得</div>
              <div className={styles.result_text}>健达龙年微信红包封面</div> */}
              <img
                className={styles.get_img_title}
                src={RedPackageCover}
                alt=""
              />
              <div>
                <img className={styles.result_rmk} src={ResultRmk} alt="" />
              </div>
              <div className={styles.unregister_box}>
                {registered ? (
                  <></>
                ) : (
                  <>
                    <img
                      alt=""
                      onClick={this.getPackage}
                      className={styles.now_get_button}
                      src={NowGetButton}
                    />
                    <img
                      className={styles.register_rmk}
                      src={RegisterRmk}
                      alt=""
                    />
                  </>
                )}
              </div>
              <div>
                {registered ? (
                  <img
                    alt=""
                    onClick={this.getPackage}
                    className={styles.get_button}
                    src={GetButton}
                  />
                ) : (
                  <img
                    alt=""
                    onClick={this.goRegiser}
                    className={styles.register_button}
                    src={RegisterButton}
                  />
                )}
                <img
                  alt=""
                  onClick={() => {
                    navigateToMiniHome(
                      "/pages/userPackage/FY2324CNYBeSpoke?scene=luckydraw",
                      () => {
                        this.props.navigate("/");
                      }
                    );
                    window._ha(
                      "send",
                      "action",
                      "cny_activity2_receivepage_gotovideo_click",
                      {
                        campaign_id: CampaignIds.activity2,
                        channel: getChannel(),
                        code: getCode(),
                        gift_type: getGiftType(),
                        is_member: "member",
                      }
                    );
                  }}
                  className={styles.customized_button}
                  src={CustomizedButton}
                />
              </div>
            </div>
          )}

          {/* 其他奖品 */}
          {detail.lottery_result !== 5 && (
            <div className={styles.card_box}>
              {/* <div className={styles.result_title}>恭喜你获得</div>
                <div className={styles.result_text}>
                  {awardCards[this.detail.lottery_result]["name"]}
                </div> */}
              <img
                className={styles.get_img_title}
                src={awardCards[detail.lottery_result].title}
                alt=""
              />
              <div>
                <img
                  alt=""
                  className={
                    styles[awardCards[detail.lottery_result]["rmkClassName"]]
                  }
                  src={awardCards[detail.lottery_result].rmk}
                />
              </div>
              <div className={styles.card_content}>
                <div
                  className={styles.card}
                  style={{
                    backgroundImage: `url(${
                      awardCards[detail.lottery_result].cover
                    })`,
                  }}
                >
                  <img src={IpImg} className={styles.ip_img} alt="" />

                  {detail.lottery_result === 1 ? (
                    <>
                      <div className={styles.tzl_code}>{detail.code}</div>
                      <div className={styles.tzl_end_date}>
                        {detail.last_time}
                      </div>
                      <div
                        className={styles.tzl_copy_button}
                        onClick={() => {
                          // 天真蓝复制code
                          this.handlerCopy(detail.code);
                        }}
                      ></div>
                    </>
                  ) : (
                    ""
                  )}

                  {detail.lottery_result === 2 ? (
                    <>
                      <div className={styles.ks_code}>{detail.code}</div>
                      <div className={styles.ks_end_date}>
                        {detail.last_time}
                      </div>
                      <div
                        className={styles.ks_copy_button}
                        onClick={() => {
                          // 凯叔复制code
                          this.handlerCopy(detail.code);
                        }}
                      ></div>
                    </>
                  ) : (
                    ""
                  )}

                  {detail.lottery_result === 3 ? (
                    <>
                      <div className={styles.tpp_code}>{detail.code}</div>
                      <div className={styles.tpp_password}>{detail.pwd}</div>
                      <div className={styles.tpp_end_date}>
                        {detail.last_time}
                      </div>
                      <div
                        className={styles.tpp_copy_button}
                        onClick={() => {
                          // 淘票票复制卡号
                          this.handlerCopy(detail.code);
                        }}
                      ></div>
                      <div
                        className={styles.tpp_copy_p_button}
                        onClick={() => {
                          // 淘票票复制密码
                          this.handlerCopy(detail.pwd, "pass");
                        }}
                      ></div>
                    </>
                  ) : (
                    ""
                  )}

                  {detail.lottery_result === 4 ? (
                    <>
                      <div className={styles.aqiyi_code}>{detail.code}</div>
                      <div className={styles.aqiyi_end_date}>
                        {detail.last_time}
                      </div>
                      <div
                        className={styles.aqiyi_copy_button}
                        onClick={() => {
                          // 爱奇艺复制code
                          this.handlerCopy(detail.code);
                        }}
                      ></div>
                    </>
                  ) : (
                    ""
                  )}
                </div>
                <div className={styles.option_rmk}>兑换方式见活动规则</div>
              </div>
              {registered ? (
                <div>
                  <img
                    src={CustomizedRmk}
                    className={styles.customized_rmk}
                    alt=""
                  />
                  <img
                    onClick={() => {
                      navigateToMiniHome(
                        "/pages/userPackage/FY2324CNYBeSpoke?scene=luckydraw",
                        () => {
                          this.props.navigate("/");
                        }
                      );
                    }}
                    src={GoButton}
                    className={styles.go_button}
                    alt=""
                  />
                </div>
              ) : (
                <div>
                  <img
                    alt=""
                    className={
                      detail.lottery_result === 3
                        ? styles.tpp_get_rmk
                        : styles.get_rmk
                    }
                    src={detail.lottery_result === 3 ? TPPGetRmk : GetRmk}
                  />
                  <img
                    alt=""
                    onClick={this.goRegiser}
                    className={styles.register_button}
                    src={RegisterButton}
                  />
                  <img
                    alt=""
                    onClick={() => {
                      navigateToMiniHome(
                        "/pages/userPackage/FY2324CNYBeSpoke?scene=luckydraw",
                        () => {
                          this.props.navigate("/");
                        }
                      );

                      window._ha(
                        "send",
                        "action",
                        "cny_activity2_receivepage_gotovideo_click",
                        {
                          campaign_id: CampaignIds.activity2,
                          channel: getChannel(),
                          code: getCode(),
                          gift_type: getGiftType(),
                          is_member: "notmember",
                        }
                      );
                    }}
                    className={styles.customized_button}
                    src={CustomizedButton}
                  />
                </div>
              )}
            </div>
          )}
        </BaseBackground>

        {copySuccess ? (
          <Modal>
            <img
              onClick={this.closeCopySuccess}
              className={styles.copy_success_img}
              src={CopySuccess}
              alt=""
            />
          </Modal>
        ) : (
          ""
        )}

        <MyRewardButton
          onClick={() => {
            this.props.navigate("/activity_my_award_2", {
              replace: true,
            });

            window._ha(
              "send",
              "action",
              "cny_activity2_receivepage_mygift_click",
              {
                campaign_id: CampaignIds.activity2,
                channel: getChannel(),
                code: getCode(),
                gift_type: getGiftType(),
                is_member: IsRegistered() ? "member" : "notmember",
              }
            );
          }}
        />
      </>
    );
  }
}

export default EnhanceUseNavigate(Index);
